package com.hucc.sqlitedemo;

import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 演示查询sdcard数据库表中的数据适配到ListView中
 * Created by l on 2017/5/10.
 */

public class SimpleActivity extends AppCompatActivity {

    private ListView mListView;
    private SQLiteDatabase db;
    private SQLiteHelper helper;

    private final String DATABASE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/vote";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        mListView = (ListView)findViewById(R.id.list_view);
        helper = new SQLiteHelper(this);
        /**
         * openDatabase(String path, CursorFactory factory, int flags)
         *  String path 表示当前打开数据库存放的路径
         *  CursorFactory factory
         *  int flags 表示打开数据库的操作模式
         */
        db = openDatabase(this);
        db = helper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from " + Constant.TABLE_NAME, null);

        /**
         * 将数据源数据加载到适配器中
         * SimpleCursorAdapter(Context context, int list_item, Cursor c, String[] from, int[] to, int flags)
         *  Context context 上下文对象
         *  int list_item 表示适配器控件中每项item 的布局id
         *  Cursor c 表示Cursor 数据源
         *  String[] from 表示cursor 中数据表字段的数组
         *  int[] to 表示展示字段对应值的控件资源id
         *  int flags 设置适配器的标记
         */
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_item, cursor, new String[]{Constant._ID, Constant.NAME, Constant.PHONE},
                                              new int[]{R.id.tv_id, R.id.tv_name,R.id.tv_phone},
                                              SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        mListView.setAdapter(adapter);
    }

    private SQLiteDatabase openDatabase(Context context) {
        File file = new File(DATABASE_PATH);
        //查看数据库文件是否存在
        if (file.exists()){
            Log.i("test", "存在数据库");
            // 存在则直接返回打开的数据库
            return SQLiteDatabase.openOrCreateDatabase(file, null);
        }else{
              //不存在先创建文件夹
            File path = new File(DATABASE_PATH);
            Log.i("test", "pathStr="+path);
            if (path.mkdir()){
                Log.i("test", "创建成功");
            }else{
                Log.i("test", "创建失败");
            }
            try {
                //得到资源
                AssetManager am = context.getAssets();
                //得到数据库的输入流
               // InputStream is = am.open(Constant.DATABASE_NAME);
                // InputStream is = am.open("info.db");
                InputStream is = am.open(String.valueOf(R.raw.info));
                Log.i("test", is+"");
                //用输出流写到SDcard上面
                FileOutputStream fos = new FileOutputStream(file);
                Log.i("test", "fos="+fos);
                Log.i("test", "file="+file);
                //创建byte数组  用于1KB写一次
                byte[] buffer = new byte[1024];
                int count = 0;
                while ((count = is.read(buffer))>0){
                    Log.i("test", "得到");
                    fos.write(buffer, 0, count);
                }
                fos.flush();
                fos.close();
                is.close();
            }catch (IOException e){
                e.printStackTrace();
                return null;
            }
        }
        return openDatabase(context);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        db.close();
    }
}
